<?php

/*
采购订单列表
*/
namespace Modules\Purchasing\Http\Repositories;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Modules\Purchasing\Models\Provisional;
use Modules\Purchasing\Models\Provisionalschedule;
use Illuminate\Support\Facades\DB;
use Catch\Exceptions\FailedException;
use Modules\Base\Service\BoxService;
use Modules\Purchasing\Models\Supplier;
use Modules\Purchasing\Models\Supplierschedule;
use Modules\Purchasing\Models\Purchaseorder;
use Modules\Purchasing\Models\Purchaseorderschedule;
use Modules\Warehouse\Models\Storagelocation;
use Modules\Purchasing\Models\Inspectionlist;
use Modules\Purchasing\Models\Inspectionlistcheck;
use Modules\Purchasing\Models\Purchasewarehousing;
use extend\services\warehouse\{warehouseService};//引入自定义类
use Modules\Purchasing\Models\PurchasewarehousingDetail;
use App\Services\KingDeeService;
use App\Services\InventoryService;
use Modules\Purchasing\Models\PurchasewarehousingGiveaway;//赠品汇总表
use App\Enums\InvTransDocType;
use Modules\Salesmanagement\Models\SalesoutAttached;
use Modules\Salesmanagement\Models\Salesout;
use Modules\Salesmanagement\Models\SalesoutTiaoma;
use Modules\Purchasing\Models\PurchasewarehousingMateriel;
use Modules\Purchasing\Models\Inspectionlisttable;
use App\Services\RedisLockService;
use Modules\Systemsetting\Models\Systemsetting;
use Modules\Purchasing\Models\Barcodeprinting;

class PurchasewarehousReget
{
   
    /*
    数据列表
    */
    public static function processing()
    {
        
        $data = Provisionalschedule::select('purchaseorder_id','purchaseorderschedule_id','barcode','putquantity','purchasewarehousing_id','storagelocation_id','id','ifst')
        ->whereNotNull('purchasewarehousing_id')
        ->whereNotNull('storagelocation_id')
        ->where('ifst',0)
        ->get()
        ->toArray();
       
        $datares = [];
        foreach ($data as $k=>$v){
            if($v['ifst']==0){
                $datares['purchasewarehousing_id'] = $v['purchasewarehousing_id'];
                $datares['barcode'] = $v['barcode'];
                $datares['putquantity'] = $v['putquantity'];
                $datares['storagelocation'] = $v['storagelocation_id'];
                $datares['purchaseorder_id'] = $v['purchaseorder_id'];
                $datares['purchaseorderschedule_id'] = $v['purchaseorderschedule_id'];
                
                $fmasterid = Purchaseorderschedule::select('fmasterid')->where('id',$v['purchaseorderschedule_id'])->first();
                Provisionalschedule::where('id',$v['id'])->update(['ifst'=>1]);
                $datares['fmasterid'] = $fmasterid['fmasterid'];
                
                PurchasewarehousingDetail::insert($datares);
            }
        }

    }
    
    
    /*
    数据列表
    */
    public static function list($data = [])
    {
        return self::getBuilder($data)->paginate($data['limit'] ?? 20);
    }


     /**
     *查询列表
     *
     * @param array $data
     * @return Builder
     */
    public static function getBuilder(array $data = []): Builder
    {
      
       
        $builder = Purchasewarehousing::query();
        if (isset($data['warehosnumber'])) {
            $builder->where('warehosnumber', 'like', "%{$data['warehosnumber']}%");
        }
        if (isset($data['remarks'])) {
            $builder->where('remarks', 'like', "%{$data['remarks']}%");
        }

        if (isset($data['state'])) {
            $builder->where('state',$data['state']);
        }
        
        if (isset($data['incomingtype'])) {
            $builder->where('incomingtype',$data['incomingtype']);
        }

        if (isset($data['writestate'])) {
            $builder->where('writestate',$data['writestate']);
        }
        

        // // 采购订单号
        if (isset($data['fbillno'])) {
            $res = Purchaseorder::select('id')->where('fbillno', 'like', "%{$data['fbillno']}%")
            // ->join('purchaseorderschedule as purchaseorderschedule', 'purchaseorderschedule.purchaseorder_id', '=', 'purchaseorder.id')
            ->get()
            ->toArray();
            $purchaseorder_id = [];
            foreach($res as $k=>$v){
                $purchaseorder_id[] = $v['id'];
            }

             $resdata = provisionalschedule::select('purchasewarehousing_id')
             ->whereIn('purchaseorder_id',$purchaseorder_id)
             ->get()
             ->toArray();

             $purchasewarehousing_id = [];
             foreach($resdata as $k=>$v){
                $purchasewarehousing_id[] = $v['purchasewarehousing_id'];
             }
             $builder->whereIn('id',$purchasewarehousing_id);
        }
        
        $builder->orderBy('id', 'desc');
        return $builder;
    }
     /*
    数据添加方法
    */
    public static function create(array $data)
    {
        $Purchasewarehousing = new Purchasewarehousing;
        return self::createOrSave($Purchasewarehousing, $data);
    }

    //数据添加方法
    public static function createOrSave(Purchasewarehousing $Purchasewarehousing,$data)
    {
        
            $actual_number = Supplierschedule::select(DB::raw('SUM(actual_number) as actual_number'))->where('supplier_id',$data['supplier_id'])->groupby(['supplier_id'])->first();
            
            //供应商多少箱号入库多少箱号
            if($actual_number['actual_number'] != count($data['detailscheck_all'])){
                return throw new FailedException('亲！供应商送货箱数和入库箱号不一致，亲扫描完在入库哦');
            }
         
            // $InterorgOpening = Systemsetting::Opening('*',['argument_code'=>'InterorgOpening']);

             //判断是否是组织间
             $intertissue = 0;
             if($data['fpurchaseorgid_number']==106&&$data['fsupplierid_number']=='VEN00721'){
                $intertissue = 1; 
             }
             
                

            //1.入库的时候，扫第一个码，得出是哪个供应商，哪个采购订单号，要识别这个采购订单号的暂收情况和检验情况，满足改采购订单的已暂收的全部物料已经全部质检完成，才允许采购入库操作，而且采购入库必须把这个采购订单号的已暂收的全部物料入库
            // $data = Provisionalschedule::query()->select('purchasewarehousing_id','provisional_id','inspectionlist_id')->whereIn('id',$data['detailscheck_all'])->get()->toArray();
            if(empty($data['detailscheck_all'])){
                throw new FailedException('参数出错');
            }
           
          
            $provisional_id = [];
            //组织间无需检验和暂收，直接扫描入库
            if($intertissue==0){
   
                        foreach($data['detailscheck_all'] as $k=>$v){
                             
                            $provisional_id[] = $v['provisional_id'];
                            $Provisionalschedule = Provisionalschedule::query()->select(
                                'id',
                                'provisional_id',
                                'inspectionlist_id',
                                'purchasewarehousing_id',
                                'inspectionlisttable_id',
                                'purchaseorder_id',
                                'purchaseorderschedule_id',
                                'supplier_id',
                                'supplierschedule_id',
                                )->where('id',$v['provisionalschedule_id'])
                                ->first();
                  
                            if(!empty($Provisionalschedule['purchasewarehousing_id'])){
                                throw new FailedException('无法提交，已有条码入库了，不是一张单，请检查在提交');
                            }

                            //判断是否质检完成
                            // $Inspectionlist = Inspectionlist::where('id',$v['inspectionlist_id'])->where('inspectionresult',1)->first()->toArray();
                            // $provisional = Provisional::where('id',$v['provisional_id'])->where('state',1)->first()->toArray();
                            // if(empty($Inspectionlist)||empty($provisional)) throw new FailedException('扫描出错无法入库,该暂收单号未审核或者未检查完成，请查看数据。');
                            $datares = Provisionalschedule::select('inspectionlisttable_id','inspectionlist_id')
                            ->where('inspectionlisttable_id',$Provisionalschedule['inspectionlisttable_id'])
                            ->where('provisional_id',$Provisionalschedule['provisional_id'])
                            ->where('purchaseorder_id',$Provisionalschedule['purchaseorder_id'])
                            ->where('purchaseorderschedule_id',$Provisionalschedule['purchaseorderschedule_id'])
                            ->where('supplier_id',$Provisionalschedule['supplier_id'])
                            ->where('supplierschedule_id',$Provisionalschedule['supplierschedule_id'])
                            ->get()
                            ->toArray();
                            $inspectionlist_id = 0;

                            foreach($datares as $ks=>$vs){
                                    if(!empty($vs['inspectionlist_id'])){
                                        $Inspectionlist = Inspectionlist::where('id',$vs['inspectionlist_id'])->where('decision',0)->first(); 
                                        if(!empty($Inspectionlist)) {
                                            throw new FailedException('亲！拒收状态无法入库');
                                        }
                                        // $inspectionlist_id ++;
                                    }
                            }
                            // if($inspectionlist_id==0){
                            //     throw new FailedException('质检单未完成审核，请检查是否质检完成了');
                            // }
                            
                            //查看总的供应送货单数
                            $supplier_id_cont =  Provisionalschedule::query()->select('supplier_id')->where('supplier_id',$Provisionalschedule['supplier_id'])->count();
                    }
                
                    $sj = array_unique($provisional_id);
                    //1.必须同一张暂收单
                    if(count($sj) > 1){
                        return  throw new FailedException('亲！扫描入库箱数不同一张暂收单，请检查');
                    }
                    //2.整单暂收。暂单入库
                    $coud =  Provisionalschedule::query()->select('provisional_id')->where('provisional_id',$data['detailscheck_all'][0]['provisional_id'])->count();//查看总的暂收单数
                    if($coud != count($data['detailscheck_all'])){
                        return  throw new FailedException('亲！扫描入库箱数和暂收箱数不一致无法录入');
                    }
                    
                    //供应商多少箱号入库多少箱号
                    if($supplier_id_cont != count($data['detailscheck_all'])){
                        return throw new FailedException('亲！供应商送货单暂收箱数和入库箱号不一致，不能入库哦');
                    }
                    
            }
            
       
            
          
        try {
             //开始起事务
            DB::beginTransaction();
       
            $Purchasewdata = [];
            $Purchasewdata['warehosnumber'] = \App\Services\UnitService::createDocno(\App\Enums\OrderNoPrefix::NO_CG->value);
            $Purchasewdata['creator_id'] = $data['creator_id'];//创建人
            $Purchasewdata['remarks'] = $data['remarks'];
            $Purchasewdata['incomingtype'] = $intertissue;
           
            $Purchasewarehousing->fill($Purchasewdata);
            $Purchasewarehousing->save();
            
          
            $Purchasewarehousing->detailscheckAll()->createMany($data['detailscheck_all']);
  
            //金蝶推送
            $alike = [];
           
            $fbillno = Storagelocation::select(
                'stash.fnumber',
                'stash.fname',
                'stash.fuseorgid_number',
                'stash.fuseorgid_name',
                'owning_id',
                'storagelocation.warehousecode',
                'storagelocation.repositoryname',
                'storagelocation.id'
                )
            ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
            ->where('storagelocation.id',$data['detailscheck_all'][0]['storagelocation'])
            ->first();
            if(empty($fbillno)){
                return throw new FailedException('库位出错');
            }
  
            foreach($data['detailscheck_all'] as $k=>$v){    
             
             
                     //组织间无需审核推送金蝶
                    if($intertissue==1){

                            if(isset($alike[$v['purchaseorder_id'].$v['purchaseorderschedule_id'].$v['storagelocation']])){
                                    
                                $alike[$v['purchaseorder_id'].$v['purchaseorderschedule_id'].$v['storagelocation']]['putquantity'] +=$v['putquantity'];
                            }else{

                                $alike[$v['purchaseorder_id'].$v['purchaseorderschedule_id'].$v['storagelocation']]['storagelocation'] = $v['storagelocation'];
                                $alike[$v['purchaseorder_id'].$v['purchaseorderschedule_id'].$v['storagelocation']]['purchaseorder_id'] = $v['purchaseorder_id'];
                                $alike[$v['purchaseorder_id'].$v['purchaseorderschedule_id'].$v['storagelocation']]['purchaseorderschedule_id'] = $v['purchaseorderschedule_id'];
                                $alike[$v['purchaseorder_id'].$v['purchaseorderschedule_id'].$v['storagelocation']]['putquantity'] = $v['putquantity'];
                            }
        
                            $fsupplierid_number = Purchaseorder::query()->select('fsupplierid_number','fpurchaseorgid_number','fbillno')->where('id',$v['purchaseorder_id'])->first()->toArray();
                            $dataPurchaseorderscheduleTwo = Purchaseorderschedule::query()->select('fmaterialid','funitid_number','fownertypeid','fownerid_number','fownerid_name')
                            ->where('id',$v['purchaseorderschedule_id'])
                            ->first();
                          
            
                            if(empty($fsupplierid_number)||empty($dataPurchaseorderscheduleTwo)) return throw new FailedException('数据出错');
            
                            $inventory = [
                                    'org_code'=>$fsupplierid_number['fpurchaseorgid_number'],
                                    'cargo_code'=>$dataPurchaseorderscheduleTwo['fownerid_number'],
                                    'supplier_code'=>$fsupplierid_number['fbillno'],
                                    'doc_id'=>$Purchasewarehousing['id'],
                                    'docno'=>$Purchasewdata['warehosnumber'], 
                                    'doc_type'=>InvTransDocType::PURCHASE_RECEIPT->value,
                                    'material_no'=>$dataPurchaseorderscheduleTwo['fmaterialid'],
                                    'location'=>$fbillno['warehousecode'],
                                    'qty'=>$v['putquantity'],
                                    'unit'=>$dataPurchaseorderscheduleTwo['funitid_number'],
                                    'lotnum'=>$v['barcode'],
                                ];
                            
                            $data = InventoryService::addInv($inventory);

                    }else{
                           
                        Provisionalschedule::query()->where('id',$v['provisionalschedule_id'])->update(
                               [
                                   'purchasewarehousing_id'=>$Purchasewarehousing['id'],
                                   'putquantity'=>$v['putquantity'],
                                   'storagelocation_id'=>$v['storagelocation'],
                               ]
                            );
                    }
        
           }



            //组织间无需审核推送金蝶
            $Model = [];
            if($intertissue==1){
                    //合并后数据
                    foreach($alike as $k=>$v){

                        $Model[$k]['FGIVEAWAY'] = 'false';
                        $Model[$k]['FGIVEAWAYQTY'] = 0;
                            
                        $dataPurchaseorderschedule = Purchaseorderschedule::query()->select('fid','fseq','fmaterialid','funitid_number','purchaseorder_id','fentryid')
                        ->where('id',$v['purchaseorderschedule_id'])
                        ->where('purchaseorder_id',$v['purchaseorder_id'])
                        ->first()
                        ->toArray();

                        $caigou = Purchaseorder::query()->select('fbillno','fpurchaseorgid_number')->where('id',$dataPurchaseorderschedule['purchaseorder_id'])->first();
                        if(empty($caigou)||empty($dataPurchaseorderschedule)) return throw new FailedException('采购数据查询出错');

                        $Model[$k]['FORGID'] = $caigou['fpurchaseorgid_number'];//编码
                        $Model[$k]['FSRCBILLNO'] = $caigou['fbillno'];
                        $Model[$k]['FSRCSEQ'] = $dataPurchaseorderschedule['fseq'];
                        $Model[$k]['FMATERIALID'] = $dataPurchaseorderschedule['fmaterialid'];    
                        $Model[$k]['FUNITID'] = $dataPurchaseorderschedule['funitid_number'];
                        $Model[$k]['FQTY'] = $v['putquantity'];

                        $Model[$k]['FOwnerTypeId'] = 'BD_OwnerOrg';//货主类型
                        $Model[$k]['FOwnerId'] = $caigou['fpurchaseorgid_number'];//货主编码

                        $Model[$k]['FSRCID'] = $dataPurchaseorderschedule['fid'];
                        $Model[$k]['FSRCENTRYID'] = $dataPurchaseorderschedule['fentryid'];//单据合并

                        $Model[$k]['FSTOCKID']= $fbillno['fnumber'];
                        
                    }
                            
                   
                    //更新状态
                    Purchasewarehousing::query()->updateOrCreate(['id' => $Purchasewarehousing['id']], [
                        'state' => 1,
                        'writestate' => 1,
                    ]);  


                    $FEntity = [];
                    foreach($Model as $k=>$v){
                        $FEntity[$v['FORGID']][$k]['FSRCSEQ'] = $v['FSRCSEQ'];
                        $FEntity[$v['FORGID']][$k]['FMATERIALID'] = $v['FMATERIALID'];
                        $FEntity[$v['FORGID']][$k]['FUNITID'] = $v['FUNITID'];
                        $FEntity[$v['FORGID']][$k]['FQTY'] = $v['FQTY'] - $v['FGIVEAWAYQTY'];
                        $FEntity[$v['FORGID']][$k]['FSTOCKID'] = $v['FSTOCKID'];
                        $FEntity[$v['FORGID']][$k]['FGIVEAWAY'] = $v['FGIVEAWAY'];
                        $FEntity[$v['FORGID']][$k]['FSRCBILLNO'] = $v['FSRCBILLNO'];
                        $FEntity[$v['FORGID']][$k]['FSRCID'] = $v['FSRCID'];
                        $FEntity[$v['FORGID']][$k]['FSRCENTRYID'] = $v['FSRCENTRYID'];
                        $FEntity[$v['FORGID']][$k]['FGIVEAWAYQTY'] = $v['FGIVEAWAYQTY'];
                        $FEntity[$v['FORGID']][$k]['FOwnerTypeId'] = $v['FOwnerTypeId'];
                        $FEntity[$v['FORGID']][$k]['FOwnerId'] = $v['FOwnerId'];
                    }
                
                    foreach($FEntity as $k=>$v){
                                $order = [
                                    'FID'=>0,
                                    'FORGID'=>$k,//组织（传编码）
                                    'FBillNo'=>$Purchasewdata['warehosnumber'],
                                    'FDATE'=>date('Y-m-d H:i:s',time()),
                                    'FBILLTYPEID'=>"PUR_InStock",
                                    //'FSRCBILLNO'=>$k,
                                    'FEntity'=>array_values($v),
                                ];
                            //金蝶推送
                            (new KingDeeService())->form('TVJB_DJWMSDJ')->invokeSave($order);
                    }

            }

            
            DB::commit();
            return true;
            
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException($e);
        }
        
    }

    //修改
    public static function createUpdate($data,$modifier)
    {
        // $Provisionalschedule = Provisionalschedule::select('purchasewarehousing_id')->where('id',$data[0]['id'])->first();
        //      if(empty($Provisionalschedule)){
        //         throw new FailedException('亲，数据出错');
        //      }
        
        try {
            //开始起事务
            DB::beginTransaction();
        
            foreach($data as $k=>$v){
                PurchasewarehousingDetail::query()->where('id',$v['id'])->update(
                    ['putquantity'=>$v['putquantity']]
                ); 
            }

            Purchasewarehousing::query()->where('id',$data[0]['purchasewarehousing_id'])->update(
                ['modifier'=>$modifier]
            ); 
            DB::commit();
            return ['code'=>1000,'message'=>'修改成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('服务器飞出地球了请联系技术找回');
        }

    }


    
    //汇总数据修改
    public static function createUpdatesummary($data,$modifier)
    {
       
        $Provisionalschedule = Provisionalschedule::select('purchasewarehousing_id')->where('purchasewarehousing_id',$data[0]['purchasewarehousing_id'])->first();
        if(empty($Provisionalschedule)){
           throw new FailedException('亲，数据出错');
        }
        try {
            //开始起事务
            DB::beginTransaction();
            $PurchasewarehousingGiveaway = new PurchasewarehousingGiveaway();
            
            foreach($data as $k=>$v){
                $PurchasewarehousingGiveaway->query()
                ->where('provisional_id',$v['provisional_id'])
                ->where('purchaseorder_id',$v['purchaseorder_id'])
                ->where('purchaseorderschedule_id',$v['purchaseorderschedule_id'])
                ->where('supplier_id',$v['supplier_id'])
                ->where('purchasewarehousing_id',$v['purchasewarehousing_id'])
                ->where('inspectionlisttable_id',$v['inspectionlisttable_id'])
                ->delete(); 

                $datares = [
                    'giveaway'=>$v['giveaway'],
                    'provisional_id'=>$v['provisional_id'],
                    'purchaseorder_id'=>$v['purchaseorder_id'],
                    'purchaseorderschedule_id'=>$v['purchaseorderschedule_id'],
                    'supplier_id'=>$v['supplier_id'],
                    'purchasewarehousing_id'=>$v['purchasewarehousing_id'],
                    'inspectionlisttable_id'=>$v['inspectionlisttable_id'],
                ];
                $PurchasewarehousingGiveaway->insert($datares);
                // $PurchasewarehousingGiveaway->save();  
            }

            Purchasewarehousing::query()->where('id',$Provisionalschedule->purchasewarehousing_id)->update(
                ['modifier'=>$modifier]
            );

            DB::commit();
            return ['code'=>1000,'message'=>'修改成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('服务器飞出地球了请联系技术找回');
        }

    }

    /**
     * 查询一条数据
     */
    public static function find($id)
    {
        return Provisional::query()->with('detailscheckAll')->find($id);
    }

    /**
     * @param $id
     * @return void
     */
    public static function delete($id)
    {
       
        try {
            //开始起事务
            DB::beginTransaction();
            Purchasewarehousing::query()->where('id',$id)->delete();
            $Provisionalschedule_id = Provisionalschedule::select('id')->where('purchasewarehousing_id',$id)->get()->toArray();
            foreach ($Provisionalschedule_id as $k=>$v){
                    $data = Provisionalschedule::query()->where('id',$v['id'])->update([
                    'giveaway'=>null,
                    'putquantity'=>null,
                    'purchasewarehousing_id'=>null,
                    'storagelocation_id'=>null,
                ]);
            }
            
           
            DB::commit();
            return '删除成功';
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('服务器飞出地球了请联系技术找回');
        }


    }
    
     /* 采购入单审核审核
     * @param $id
     * @return void
     */
    public static function auditupdate($id)
    {
        
        //金蝶推送
        //汇总数据
        // $data = Provisionalschedule::query()
        // ->select(
        //     'provisional_id',
        //     'purchaseorder_id',
        //     'supplier_id',
        //     'supplierschedule_id',
        //     'storagelocation_id',
        //     'purchasewarehousing_id',
        //     'purchaseorderschedule_id',
        //     'caigoucreator_id',
        //     DB::raw('SUM(quantityreceived) as quantityreceived'),
        //     // DB::raw('SUM(giveaway) as giveaway'),
        //     DB::raw('SUM(putquantity) as putquantity'),
        //     )
        // ->where('purchasewarehousing_id',$id)
        // ->groupby(['provisional_id','purchaseorder_id','supplier_id','supplierschedule_id','storagelocation_id','purchasewarehousing_id','caigoucreator_id','purchaseorderschedule_id'])
        // ->get()
        // ->toArray();

        $data =  PurchasewarehousingDetail::select('purchasewarehousing_id', DB::raw('SUM(putquantity) as putquantity'),'storagelocation','purchaseorder_id','purchaseorderschedule_id','fmasterid')
        ->where('purchasewarehousing_id',$id)->groupby(['purchasewarehousing_id','storagelocation','purchaseorder_id','purchaseorderschedule_id','fmasterid'])->get()
        ->toArray();
      

        //明细数据
        // $dataProvisionalschedule = Provisionalschedule::query()
        // ->select(
        //         'provisional_id',
        //         'purchaseorder_id',
        //         'supplier_id',
        //         'supplierschedule_id',
        //         'storagelocation',
        //         'storagelocation_id',
        //         'purchasewarehousing_id',
        //         'caigoucreator_id',
        //         'quantityreceived',
        //         'giveaway',
        //         'putquantity',
        //         'barcode',
        //         'inspectionlist_id',
        //         'inspectionlisttable_id',
        //     )
        // ->where('purchasewarehousing_id',$id)
        // ->get()
        // ->toArray();
 
        //明细数据
        $dataProvisionalschedule =  PurchasewarehousingDetail::select('purchasewarehousing_id', 'putquantity','storagelocation','purchaseorder_id','purchaseorderschedule_id','fmasterid','barcode')
        ->where('purchasewarehousing_id',$id)->get()->toArray();

        //判断是否质检完成和暂收完成
        //1.物料id是否等于检验单附表id
        //2.判断简单附表id检验单是否合格
    //    $inspectionlist_id = 0;
    //     foreach($dataProvisionalschedule as $k=>$v){
    //         $Inspectionlist = Inspectionlist::where('id',$v['inspectionlist_id'])->where('decision',0)->first();
    //         if(!empty($Inspectionlist)){
    //             throw new FailedException('亲！扫描出错无法入库,质检拒收，请查看数据。');
    //         }
    //         if(!empty($v['inspectionlist_id'])){
    //                 $inspectionlist_id ++;
    //         }
    //     }
        // if(count($data) <= $inspectionlist_id){
        //     throw new FailedException('扫描出错无法入库,质检未完成，请查看数据。');
        // }
        
    
        $datares = Purchasewarehousing::query()->select('warehosnumber')->where('id',$id)->first()->toArray();//采购订单表

        if(empty($data)||empty($datares)) throw new FailedException('入库数据出错请联系技术处理');
           
            $Model = [];
            $kingDeeService = new warehouseService();
            $resdata = $kingDeeService->warehousedataApiTwo();
            
            foreach($data as $k=>$v){
                //赠品
                // if(isset($data['detailsAll'])){
                    $giveaway = PurchasewarehousingGiveaway::select('giveaway')
                    // ->where('provisional_id',$v['provisional_id'])
                    ->where('purchaseorder_id',$v['purchaseorder_id'])
                    ->where('purchaseorderschedule_id',$v['purchaseorderschedule_id'])
                    // ->where('supplier_id',$v['supplier_id'])
                    ->where('purchasewarehousing_id',$v['purchasewarehousing_id'])
                    //->where('inspectionlisttable_id',$v['inspectionlisttable_id'])
                    ->first();
                    $Model[$k]['FGIVEAWAY'] = 'false';
                    $Model[$k]['FGIVEAWAYQTY'] = 0;
                    if(!empty($giveaway->giveaway)){
                        $Model[$k]['FGIVEAWAYQTY'] = $giveaway->giveaway;//赠品数量
                    }
                // }
                // $provisional = Provisional::where('id',$v['provisional_id'])->where('state',1)->first()->toArray();
                // $dataSupplierschedule = Supplierschedule::query()->select('purchaseorderschedule_id')
                // ->where('id',$v['supplierschedule_id'])
                // ->where('supplier_id',$v['supplier_id'])
                // ->where('purchaseorder_id',$v['purchaseorder_id'])
                // ->get()
                // ->toArray();
                // $purchaseorderschedule_id = [];
              
                // foreach($dataSupplierschedule as $ks=>$vs){
                //     $purchaseorderschedule_id[] = $vs['purchaseorderschedule_id'];
                // }

                $dataPurchaseorderschedule = Purchaseorderschedule::query()->select('fid','fseq','fmaterialid','funitid_number','purchaseorder_id','fentryid')
                ->where('id',$v['purchaseorderschedule_id'])
                ->groupby(['purchaseorder_id','fid','fseq','fmaterialid','fmaterialname','fmaterialmodel','fmodel','funitid_number','fentryid'])
                ->first()
                ->toArray();

                $caigou = Purchaseorder::query()->select('fbillno','fpurchaseorgid_number')->where('id',$dataPurchaseorderschedule['purchaseorder_id'])->first();
                if(empty($caigou)||empty($dataPurchaseorderschedule)) return throw new FailedException('采购数据查询出错');


                // $Storagelocation = Storagelocation::select(
                //     'stash.fnumber',
                //     'stash.fname',
                //     'stash.fuseorgid_number',
                //     'stash.fuseorgid_name',
                //     'owning_id',
                //     'storagelocation.warehousecode',
                //     'storagelocation.repositoryname',
                //     'storagelocation.id'
                //     )
                // ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
                // ->where('storagelocation.id',$v['storagelocation_id'])
                // ->first();
                // $Model[$k]['FORGID'] = $Storagelocation['fuseorgid_number'];
                // $Model[$k]['FOwnerId'] = $Storagelocation['fuseorgid_number'];

                $Model[$k]['FORGID'] = $caigou['fpurchaseorgid_number'];//编码
                $Model[$k]['FSRCBILLNO'] = $caigou['fbillno'];
                $Model[$k]['FSRCSEQ'] = $dataPurchaseorderschedule['fseq'];
                $Model[$k]['FMATERIALID'] = $dataPurchaseorderschedule['fmaterialid'];    
                $Model[$k]['FUNITID'] = $dataPurchaseorderschedule['funitid_number'];
                $Model[$k]['FQTY'] = $v['putquantity'];

                $Model[$k]['FOwnerTypeId'] = 'BD_OwnerOrg';//货主类型
                $Model[$k]['FOwnerId'] = $caigou['fpurchaseorgid_number'];//货主编码
                
                
                $Model[$k]['FSRCID'] = $dataPurchaseorderschedule['fid'];
                $Model[$k]['FSRCENTRYID'] = $dataPurchaseorderschedule['fentryid'];//单据合并

  
                $fbillno = DB::table('storagelocation')->select('owning_id','warehousecode','repositoryname')->where('id',$v['storagelocation'])->first();
               
                if(empty($fbillno)){
                     return throw new FailedException('库位出错');
                }

                if(isset($resdata[$fbillno->owning_id])){
                    $Model[$k]['FSTOCKID']= $resdata[$fbillno->owning_id]['FNumber'];
                }else{
                   return throw new FailedException('库位出错');
                }


                // if(isset($resdata[$v['storagelocation']])){
                //     $Model[$k]['FSTOCKID']= $resdata[$v['storagelocation']]['FNumber'];
                // }else{
                //    return throw new FailedException('库位出错');
                // }   

            }
            

        try {
            //开始起事务
            DB::beginTransaction();
            //更新及时库存
            $inventory = [];
            foreach($dataProvisionalschedule as $ks=>$vs){

                $fsupplierid_number = Purchaseorder::query()->select('fsupplierid_number','fpurchaseorgid_number','fbillno')->where('id',$vs['purchaseorder_id'])->first()->toArray();

                // $dataSupplierschedule = Supplierschedule::query()->select('purchaseorderschedule_id')
                // ->where('id',$vs['supplierschedule_id'])
                // ->where('supplier_id',$vs['supplier_id'])
                // ->where('purchaseorder_id',$vs['purchaseorder_id'])
                // ->get()
                // ->toArray();

                // $purchaseorderschedule_idTwo = [];
                // foreach($dataSupplierschedule as $kk=>$vv){
                //     $purchaseorderschedule_idTwo[] = $vv['purchaseorderschedule_id'];
                // }

                $dataPurchaseorderscheduleTwo = Purchaseorderschedule::query()->select('fmaterialid','funitid_number','fownertypeid','fownerid_number','fownerid_name')
                ->where('id',$vs['purchaseorderschedule_id'])
                ->groupby(['purchaseorder_id','fid','fseq','fmaterialid','fmaterialname','fmaterialmodel','fmodel','funitid_number','fownertypeid','fownerid_number','fownerid_name'])
                ->first()
                ->toArray();

                if(empty($fsupplierid_number)||empty($dataPurchaseorderscheduleTwo)) return throw new FailedException('数据出错');

                $fbillno = DB::table('storagelocation')->select('owning_id','warehousecode','repositoryname')->where('id',$vs['storagelocation'])->first();
                
                if(empty($fbillno)){
                     return throw new FailedException('库位出错');
                }

                 //更新库存临时表
                //  $Storagelocation = Storagelocation::select(
                //     'stash.fnumber',
                //     'stash.fname',
                //     'stash.fuseorgid_number',
                //     'stash.fuseorgid_name',
                //     'owning_id',
                //     'storagelocation.warehousecode',
                //     'storagelocation.repositoryname',
                //     'storagelocation.id'
                //     )
                // ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
                // ->where('storagelocation.id',$v['storagelocation_id'])
                // ->first();
            
                $inventory = [
                        // 'org_code'=>$Storagelocation['fuseorgid_number'],
                        // 'cargo_code'=>$Storagelocation['fuseorgid_number'],
                        'org_code'=>$fsupplierid_number['fpurchaseorgid_number'],
                        'cargo_code'=>$dataPurchaseorderscheduleTwo['fownerid_number'],//$dataPurchaseorderscheduleTwo['fownertypeid']
                        'supplier_code'=>$fsupplierid_number['fbillno'],
                        'doc_id'=>$id,
                        'docno'=>$datares['warehosnumber'], 
                        'doc_type'=>InvTransDocType::PURCHASE_RECEIPT->value,
                        'material_no'=>$dataPurchaseorderscheduleTwo['fmaterialid'],
                        'location'=>$fbillno->warehousecode,
                        'qty'=>$vs['putquantity'],
                        'unit'=>$dataPurchaseorderscheduleTwo['funitid_number'],
                        'lotnum'=>$vs['barcode'],
                    ];
                
                $data = InventoryService::addInv($inventory);
            }
            
 
            //更新状态
            Purchasewarehousing::query()->updateOrCreate(['id' => $id], [
                'state' => 1,
                'writestate' => 1,
            ]);  


            $FEntity = [];
            foreach($Model as $k=>$v){
                $FEntity[$v['FORGID']][$k]['FSRCSEQ'] = $v['FSRCSEQ'];
                $FEntity[$v['FORGID']][$k]['FMATERIALID'] = $v['FMATERIALID'];
                $FEntity[$v['FORGID']][$k]['FUNITID'] = $v['FUNITID'];
                $FEntity[$v['FORGID']][$k]['FQTY'] = $v['FQTY'] - $v['FGIVEAWAYQTY'];
                $FEntity[$v['FORGID']][$k]['FSTOCKID'] = $v['FSTOCKID'];
                $FEntity[$v['FORGID']][$k]['FGIVEAWAY'] = $v['FGIVEAWAY'];
                $FEntity[$v['FORGID']][$k]['FSRCBILLNO'] = $v['FSRCBILLNO'];
                $FEntity[$v['FORGID']][$k]['FSRCID'] = $v['FSRCID'];
                $FEntity[$v['FORGID']][$k]['FSRCENTRYID'] = $v['FSRCENTRYID'];
                $FEntity[$v['FORGID']][$k]['FGIVEAWAYQTY'] = $v['FGIVEAWAYQTY'];
                $FEntity[$v['FORGID']][$k]['FOwnerTypeId'] = $v['FOwnerTypeId'];
                $FEntity[$v['FORGID']][$k]['FOwnerId'] = $v['FOwnerId'];
            }
           
            foreach($FEntity as $k=>$v){
                        $order = [
                            'FID'=>0,
                            'FORGID'=>$k,//组织（传编码）
                            'FBillNo'=>$datares['warehosnumber'],
                            'FDATE'=>date('Y-m-d H:i:s',time()),
                            'FBILLTYPEID'=>"PUR_InStock",
                            //'FSRCBILLNO'=>$k,
                            'FEntity'=>array_values($v),
                        ];
                    //金蝶推送
                    (new KingDeeService())->form('TVJB_DJWMSDJ')->invokeSave($order);
            }

         
            DB::commit();
            return ['code'=>1000,'message'=>'审核成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException($e);
        }

    }


    /*采购入库扫描
     * @param $id
     * @return void
     */
    public static function checkPdaApi($code)
    {
      
     
        $barcode = Barcodeprinting::select('void','supplier_id','purchaseorderschedule_id','barcode')->where('barcode',$code)->first();

        if(empty($barcode)){
            return throw new FailedException('亲，该箱号不存在');
        }
 
        if($barcode['void']==1){
            return throw new FailedException('亲，该箱号已作废无法入库');
        }
        

        $data = Purchaseorderschedule::select(
        'purchaseorder.fbillno',
        'purchaseorder.fpurchaseorgid_number',
        'purchaseorder.fid',
        'purchaseorder.fpurchaseorgid_name',
        'purchaseorder.fsupplierid_number',
        'purchaseorder.fsupplierid_name',
        'purchaseorderschedule.id',
        'purchaseorderschedule.fmaterialid',
        'purchaseorderschedule.fmaterialname',
        'purchaseorderschedule.fmaterialmodel',
        'purchaseorderschedule.fmodel',
        'purchaseorderschedule.funitid_name',
        'purchaseorderschedule.fqty',
        'purchaseorderschedule.purchaseorder_id',
        'purchaseorderschedule.fownertypeid',
        'purchaseorderschedule.fownerid_number',
        'purchaseorderschedule.fownerid_name',
        'purchaseorderschedule.fmasterid',
        )
        ->join('purchaseorder as purchaseorder', 'purchaseorder.id', '=', 'purchaseorderschedule.purchaseorder_id')
        ->where('purchaseorderschedule.id',$barcode['purchaseorderschedule_id'])
        ->first();
       
        if(empty($data)) throw new FailedException('扫描出错,获取不了物料信息');

       $purchasewarehousing_id = PurchasewarehousingDetail::where('barcode',$code)->first();

        //  $purchasewarehousing_id = Provisionalschedule::select('id')->where('barcode',$code)
        //              ->whereNotNull('purchasewarehousing_id')//入库ID
        //              ->whereNotNull('storagelocation_id')//库位id
        //              ->first();

     if(!empty($purchasewarehousing_id)){
        return throw new FailedException('亲，该箱号已入库无法扫描');
     }
         
          //判断是否是组织间
        $intertissue = 0;
        $switch = 0;
        
         //组织间
         if($data['fpurchaseorgid_number']==106&&$data['fsupplierid_number']=='VEN00721'){
             
            $intertissue = 1; 
            $InterorgOpening = Systemsetting::Opening('*',['argument_code'=>'InterorgOpening']);
            //组织间开启检验
            if(empty($InterorgOpening)){
                
                $checkPdaApiinspect = self::checkPdaApiinspect($code);
                $data['supplierOrder'] = $checkPdaApiinspect['supplierOrder'];
                $data['provisional_id'] = $checkPdaApiinspect['provisional_id'];
                $data['inspectionlist_id'] = $checkPdaApiinspect['inspectionlist_id'];
                $data['provisionalschedule_id'] = $checkPdaApiinspect['provisionalschedule_id'];
                $data['quantityreceived'] = $checkPdaApiinspect['quantityreceived'];
            }else{

                $data['supplierOrder'] = '';
                $data['provisional_id'] = '';
                $data['inspectionlist_id'] = '';
                $data['provisionalschedule_id'] = '';
                $data['quantityreceived'] = '';
                
                // $checkPdaApiinspect = self::checkPdaApiinspect($code);
                // $data['supplierOrder'] = $checkPdaApiinspect['supplierOrder'];
                // $data['provisional_id'] = $checkPdaApiinspect['provisional_id'];
                // $data['inspectionlist_id'] = $checkPdaApiinspect['inspectionlist_id'];
                // $data['provisionalschedule_id'] = $checkPdaApiinspect['provisionalschedule_id'];
                // $data['quantityreceived'] = $checkPdaApiinspect['quantityreceived'];
            }
        
            
         }else{
                
                $checkPdaApiinspect = self::checkPdaApiinspect($code);
                $data['supplierOrder'] = $checkPdaApiinspect['supplierOrder'];
                $data['provisional_id'] = $checkPdaApiinspect['provisional_id'];
                $data['inspectionlist_id'] = $checkPdaApiinspect['inspectionlist_id'];
                $data['provisionalschedule_id'] = $checkPdaApiinspect['provisionalschedule_id'];
                $data['quantityreceived'] = $checkPdaApiinspect['quantityreceived'];
             
         }
       
                $data['barcode'] = $code;
                $data['purchaseorderschedule_id'] = $data['id'];
                $data['supplier_id'] = $barcode['supplier_id'];
                $data['intertissue'] = $intertissue;
                return $data;
    }
    
    /*采购入库扫描-检验
     * @param $id
     * @return void
     */
  public static function checkPdaApiinspect($code){
      $data = [];
      $data_Provisionalschedule = Provisionalschedule::select(
                'provisional.ordernumber',
                'provisionalschedule.id',
                'provisionalschedule.putquantity',
                'provisionalschedule.giveaway',
                'provisionalschedule.provisional_id',
                'provisionalschedule.purchaseorder_id',
                'provisionalschedule.supplier_id',
                'provisionalschedule.supplierschedule_id',
                'provisionalschedule.quantityreceived',
                'provisionalschedule.barcode',
                'provisionalschedule.storagelocation',
                'provisionalschedule.inspectionlist_id',
                'provisionalschedule.inspectionlisttable_id',
                'provisionalschedule.purchaseorderschedule_id',
                )
                ->join('provisional as provisional', 'provisional.id', '=', 'provisionalschedule.provisional_id')
                ->where('provisionalschedule.storagelocation_id',null)
                ->where('provisionalschedule.purchasewarehousing_id',null)
                ->where('provisionalschedule.barcode',$code)->first();
                
                if(empty($data_Provisionalschedule)){
                  return throw new FailedException('亲，未暂收检验无法入库');
                }
         
                $inspectionnumber = Inspectionlisttable::select('inspectionnumber')->where('id',$data_Provisionalschedule['inspectionlisttable_id'])->where('state',1)->first();
                
                if(empty($inspectionnumber)){
                    return throw new FailedException('亲，未质检完成无法入库');
                }
                  
                if(empty($data_Provisionalschedule)) throw new FailedException('亲，该供应商送货单箱号未暂收请暂收检验后再进行入库，谢谢配合。');
                //判断是否质检完成 查询全部该一单全部SKU
                $datares = Provisionalschedule::select('inspectionlisttable_id','inspectionlist_id')
                ->where('inspectionlisttable_id',$data_Provisionalschedule['inspectionlisttable_id'])
                ->where('provisional_id',$data_Provisionalschedule['provisional_id'])
                ->where('purchaseorder_id',$data_Provisionalschedule['purchaseorder_id'])
                ->where('purchaseorderschedule_id',$data_Provisionalschedule['purchaseorderschedule_id'])
                ->where('supplier_id',$data_Provisionalschedule['supplier_id'])
                ->where('supplierschedule_id',$data_Provisionalschedule['supplierschedule_id'])
                ->get()
                ->toArray();
                
                $inspectionlist_id = 0;
                foreach($datares as $ks=>$vs){
                        if(!empty($vs['inspectionlist_id'])){
                            $Inspectionlist = Inspectionlist::where('id',$vs['inspectionlist_id'])->where('decision',0)->first();
                            if(!empty($Inspectionlist)) {
                                return throw new FailedException('质检单拒收无法入库或者未质检完成请检查是否质检完成了');
                            }
                             //抽检判断
                            // if(!empty($v['inspectionlist_id'])){
                            //     $inspectionlist_id ++;
                            // }
                        }
                }
                
                    $Supplierschedule = Supplierschedule::select(
                    'supplier.supplierOrder',
                    'supplierschedule.purchaseorder_id',
                    'supplierschedule.purchaseorderschedule_id'
                    )
                ->join('supplier as supplier', 'supplier.id', '=', 'supplierschedule.supplier_id')
                ->where('supplier.id',$data_Provisionalschedule['supplier_id'])
                ->where('supplierschedule.purchaseorderschedule_id',$data_Provisionalschedule['purchaseorderschedule_id'])
                ->where('supplierschedule.purchaseorder_id',$data_Provisionalschedule['purchaseorder_id'])
                ->first();
                if(empty($Supplierschedule)) throw new FailedException('扫描出错,供应商物料信息获取失败');
                
                $data['supplierOrder'] = $Supplierschedule['supplierOrder'];
                $data['provisional_id'] = $data_Provisionalschedule['provisional_id'];
                $data['inspectionlist_id'] = $data_Provisionalschedule['inspectionlist_id'];
                $data['provisionalschedule_id'] = $data_Provisionalschedule['id'];
                $data['quantityreceived'] = $data_Provisionalschedule['quantityreceived'];
                return $data;
      
  }
    /**
     * @param $id
     * @return void
     */
    public static function showdata($data_res,$data)
    {
        $res = [];
        $kingDeeService = new warehouseService();
        $resdata = $kingDeeService->warehousedataApiTwo();
        $datauser = $kingDeeService->uerdata();
        $InterorgOpening = Systemsetting::Opening('*',['argument_code'=>'Saleout']);    //组织间生成采购单入库单是否开启
        if(!empty($InterorgOpening)){
               // //类型判断
                if($data_res['incomingtype']==1){
                    
                        if(isset($data['detailsAll'])){
                            $datares = PurchasewarehousingMateriel::query()
                            ->select(
                                // 'barcode',
                                'purchasewarehousing_id',
                                'fmaterialid',
                                'fmaterialname',
                                'fmaterialmodel',
                                'fmodel',
                                'funitid_number',
                                'funitid_name',
                                'fqty',
                                'fseq',
                                'storagelocation',
                                DB::raw('SUM(putquantity) as putquantity'),
                                )
                            ->where('purchasewarehousing_id',$data_res['id'])
                            ->groupby([
                                'purchasewarehousing_id',
                                'fmaterialid',
                                'fmaterialname',
                                'fmaterialmodel',
                                'fmodel',
                                'funitid_number',
                                'funitid_name',
                                'fqty',
                                'fseq',
                                'storagelocation',
                                ])
                            ->get()
                            ->toArray();
                    
                        }else{
                            $datares = PurchasewarehousingMateriel::
                            where('purchasewarehousing_id',$data_res['id'])
                            ->get()->toArray();
                            
                        }
                        foreach($datares as $k=>$v){

                            $datares[$k]['FName'] = '';
                            $datares[$k]['FNumber'] = '';
                            $datares[$k]['warehousecode'] = '';
                            $datares[$k]['repositoryname'] = '';
                            $fbillno = DB::table('storagelocation')->select('owning_id','warehousecode','repositoryname')->find($v['storagelocation']);
                            if(!empty( $fbillno )){
                                if(isset($resdata[$fbillno->owning_id])){
                                    $datares[$k]['FName'] = $resdata[$fbillno->owning_id]['FName'];
                                    $datares[$k]['FNumber'] = $resdata[$fbillno->owning_id]['FNumber'];
                                }
                                
                                $datares[$k]['warehousecode'] =$fbillno->warehousecode;
                                $datares[$k]['repositoryname'] = $fbillno->repositoryname;
                            }
                        

                            $datares[$k]['quantity'] = $v['fqty'];
                            $datares[$k]['fbillno'] = $data_res['fbillno'];
                            $datares[$k]['fsupplierid_number'] = $data_res['fsupplierid_number'];
                            $datares[$k]['fsupplierid_name'] = $data_res['fsupplierid_name'];
                            $datares[$k]['giveaway'] = '';
                        }

                }

        }else{

            if(isset($data['detailsAll'])){
                
                $datares = PurchasewarehousingDetail::query()
                ->select(
                    'purchasewarehousing_id',
                    'storagelocation',
                    'purchaseorder_id',
                    'purchaseorderschedule_id',
                    'fmasterid',
                    DB::raw('SUM(putquantity) as putquantity'),
                    
                    )
                ->where('purchasewarehousing_id',$data_res['id'])
                ->groupby([
                    'purchasewarehousing_id',
                    'storagelocation',
                    'purchaseorder_id',
                    'purchaseorderschedule_id',
                    'fmasterid'
                    ])
                ->get()
                ->toArray();
            }else{
                $datares = PurchasewarehousingDetail::
                where('purchasewarehousing_id',$data_res['id'])
                ->get()->toArray();
            }
           
    
            foreach($datares as $k=>$v){  
    
               if(isset($data['detailsAll'])){
                    $giveaway = PurchasewarehousingGiveaway::select('giveaway')
                    // ->where('provisional_id',$v['provisional_id'])
                    ->where('purchaseorder_id',$v['purchaseorder_id'])
                    ->where('purchaseorderschedule_id',$v['purchaseorderschedule_id'])
                    // ->where('supplier_id',$v['supplier_id'])
                    ->where('purchasewarehousing_id',$v['purchasewarehousing_id'])
                    // ->where('inspectionlisttable_id',$v['inspectionlisttable_id'])
                    ->first();
                    if(!empty($giveaway)){
                        $datares[$k]['giveaway'] = $giveaway->giveaway;
                    }else{
                        $datares[$k]['giveaway'] = '';
                    }
               }
               
               
                // $datares[$k]['caigoucreator_id'] =  isset($datauser[$v['caigoucreator_id']])?$datauser[$v['caigoucreator_id']]['username']:'';
             
                
                $datares[$k]['FName'] = '';
                $datares[$k]['FNumber'] = '';
                $datares[$k]['warehousecode'] = '';
                $datares[$k]['repositoryname'] = '';
                $fbillno = DB::table('storagelocation')->select('owning_id','warehousecode','repositoryname')->find($v['storagelocation']);
                if(!empty($fbillno)){
                    if(isset($resdata[$fbillno->owning_id])){
                        $datares[$k]['FName'] = $resdata[$fbillno->owning_id]['FName'];
                        $datares[$k]['FNumber'] = $resdata[$fbillno->owning_id]['FNumber'];
                    }
                    
                    $datares[$k]['warehousecode'] =$fbillno->warehousecode;
                    $datares[$k]['repositoryname'] = $fbillno->repositoryname;
                }
              
                
                               
                //合并后的物料数量
                $Purchaseorderschedule = Purchaseorderschedule::select('purchaseorder_id','fseq','fqty','fmaterialid','fmaterialname','fmaterialmodel','funitid_name')
                ->where('id',$v['purchaseorderschedule_id'])->first();
    
                
                $datares[$k]['fseq'] = $Purchaseorderschedule['fseq'];
                $datares[$k]['fmaterialid'] = $Purchaseorderschedule['fmaterialid'];
                $datares[$k]['fmaterialname'] = $Purchaseorderschedule['fmaterialname'];
                $datares[$k]['fmaterialmodel'] = $Purchaseorderschedule['fmaterialmodel'];
                $datares[$k]['funitid_name'] = $Purchaseorderschedule['funitid_name'];
                $datares[$k]['fqty'] = $Purchaseorderschedule['fqty'];
                $datares[$k]['putquantity'] = sprintf("%.4f",$v['putquantity']);
                
                $Purchaseorderdata = Purchaseorder::select('fbillno','fsupplierid_number','fsupplierid_name')->where('id',$Purchaseorderschedule['purchaseorder_id'])->first();
                $datares[$k]['fbillno'] = $Purchaseorderdata['fbillno'];//采购订单号
                $datares[$k]['fsupplierid_number'] = $Purchaseorderdata['fsupplierid_number'];
                $datares[$k]['fsupplierid_name'] = $Purchaseorderdata['fsupplierid_name'];
                
            }

        }
     

  
            return $datares;
    }


      /**
     * @param $id
     * @return void
     */
    public static function pushdataAadd($data)
    {
        $Purchasewarehousing = new Purchasewarehousing;
        return self::createOrSave_pushdataAadd($Purchasewarehousing, $data);
       
    }

    //数据添加方法
    public static function createOrSave_pushdataAadd(Purchasewarehousing $Purchasewarehousing,$data)
    {
            

        try {
             //开始起事务
            DB::beginTransaction();
            
            $Purchasewdata = [];
            $Purchasewdata['warehosnumber'] = $data['fbillno'];
            $Purchasewdata['creator_id'] = $data['creator_id'];//创建人
            $Purchasewdata['fid'] = $data['fid'];
            $Purchasewdata['fpurchaseorgid_number'] = $data['fpurchaseorgid_number'];
            $Purchasewdata['fpurchaseorgid_name'] = $data['fpurchaseorgid_name'];
            $Purchasewdata['fsupplierid_number'] = $data['fsupplierid_number'];
            $Purchasewdata['fsupplierid_name'] = $data['fsupplierid_name'];
            $Purchasewdata['fprovidercontactid'] = $data['fprovidercontactid'];
            $Purchasewdata['fproviderphone'] = $data['fproviderphone'];
            $Purchasewdata['incomingtype'] = 1;
            $Purchasewarehousing->fill($Purchasewdata);
            $Purchasewarehousing->save();
        
            $Purchasewarehousing->detailscheckAllMateriel()->createMany( $data['FEntry'] );

         DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException($e);
        }
    }


    //PDA 组织间 扫描接口
    public static function pushdatacode($code)
    {
            
        $SalesoutAttached = SalesoutTiaoma::select(
            'salesout.fbillno',
            'salesout.fsaleorgid_number',
            'salesout.fsaleorgid_name',
            'salesout.fcustomerid_number',
            'salesout.fcustomerid_name',
            'salesout_attached.fmaterialid',
            'salesout_attached.fmaterialname',
            'salesout_attached.fmaterialmodel',
            'salesout_attached.fmodel',
            'salesout_attached.funitid_number',
            'salesout_attached.funitid_name',
            'salesout_tiaoma.quantity',
            'salesout_tiaoma.barcode',
            'salesout_tiaoma.salesout_id',
            'salesout_tiaoma.salesout_attached_id',
            'salesout_attached.id',
        )
        ->join('salesout as salesout', 'salesout.id', '=', 'salesout_tiaoma.salesout_id')
        ->join('salesout_attached as salesout_attached', 'salesout_attached.id', '=', 'salesout_tiaoma.salesout_attached_id')
        ->where('salesout_tiaoma.barcode',$code)
        ->first();

        $count = SalesoutTiaoma::select('id')
        ->where('salesout_id',$SalesoutAttached['salesout_id'])
        ->count();

        $inventory = DB::table('inventory')
        ->select('org_code','material_no','location','unit','qty','lot_num')
        ->where('lot_num',$code)->first();

        if(empty($SalesoutAttached)||empty($inventory)){
            return  throw new FailedException('销售出库单没有该箱号条码');
         
        }

        $fbillno = DB::table('storagelocation')
        ->select('storagelocation.warehousecode','storagelocation.repositoryname','stash.fnumber','stash.fname','storagelocation.id')
        ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
        ->where('warehousecode',$inventory->location)->first();

        $SalesoutAttached['warehousecode'] = $fbillno->warehousecode;
        $SalesoutAttached['repositoryname'] = $fbillno->repositoryname;
        $SalesoutAttached['fnumber'] = $fbillno->fnumber;
        $SalesoutAttached['fname'] = $fbillno->fname;
        $SalesoutAttached['quantityComein'] = '';
        $SalesoutAttached['count'] = $count;
       

        return $SalesoutAttached;
    }

      // 组织间数据推送 PDA 扫描接口
      public static function pushdatacodeupdate($data)
      {

       
   

                    if(empty($data['fbillno'])){
                        return  throw new FailedException('亲！销售单号不能为空。');
                    }
                    $Purchasewarehousing = Purchasewarehousing::select('fbillno','fid','id','fpurchaseorgid_number','fsupplierid_number','warehosnumber')
                    ->where('fbillno',$data['fbillno'])
                    ->where('incomingtype',1)
                    ->first();

                    $Salesout = Salesout::select('fbillno','id')->where('fbillno',$data['fbillno'])->first();

                    //  $PurchasewarehousingMateriel_count = PurchasewarehousingMateriel::select('purchasewarehousing_id')->where('purchasewarehousing_id',$Purchasewarehousing['id'])->count();
                    //  if($PurchasewarehousingMateriel_count !== count($data['detailscheck_all'])){
                    //     return  throw new FailedException('亲！组织间销售出库单出库的数据和入库的数据不一致无法入库，请扫描完在入库');
                    //  }
                        //提交的数量和销售数量判断
                $count = 0;
                foreach($data['detailscheck_all'] as $k=>$v){
                    $count +=$v['quantityComein'];

                }

                $SalesoutAttachedfqty = SalesoutAttached::query()
                    ->select(DB::raw('SUM(fqty) as fqty'))
                    ->where('salesout_id',$Salesout['id'])
                    ->groupby(['salesout_id'])
                    ->first();

                if($count != $SalesoutAttachedfqty['fqty']){
                    throw new FailedException('销售数量没有和计划销售数据量不一致，无法提交！');
                }

                    if(empty($Purchasewarehousing)||empty($Salesout)){
                        return  throw new FailedException('亲！没有该条入库单数据');
                    }
                    $Storagelocation = Storagelocation::select(
                        'stash.fnumber',
                        'stash.fname',
                        'stash.fuseorgid_number',
                        'stash.fuseorgid_name',
                        'owning_id',
                        'storagelocation.warehousecode',
                        'storagelocation.repositoryname',
                        'storagelocation.id'
                    )
                    ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
                    ->where('storagelocation.id',$data['detailscheck_all'][0]['storagelocation'])
                    ->first();
                    if(empty($Storagelocation)){
                        return throw new FailedException('库位出错');
                    }

                $Model = [];
         try {
             //开始起事务
            DB::beginTransaction();
             foreach($data['detailscheck_all'] as $k=>$v){  
                
                // $data['detailscheck_all'][$k]['salesout_attached_id']  = 4908;

               $SalesoutTiaoma = SalesoutTiaoma::where('barcode',$v['barcode'])
                ->where('salesout_attached_id',$v['salesout_attached_id'])
                ->where('salesout_id',$Salesout['id'])
                ->first(); 

                $SalesoutAttached = SalesoutAttached::where('salesout_id',$Salesout['id'])->where('id',$SalesoutTiaoma['salesout_attached_id'])->first();  
                if(empty($SalesoutAttached)){
                    return  throw new FailedException('亲！该条销售出库单号没有品号为'.$v['fmaterialid'].'的数据，不能入库');
                }      

                //  $Model[$k]['FGIVEAWAY'] = 'false';
                //  $Model[$k]['FGIVEAWAYQTY'] = 0;//赠品数量

                 $PurchasewarehousingMateriel = PurchasewarehousingMateriel::select(
                     'fmaterialid',
                     'fmaterialname',
                     'fmaterialmodel',
                     'fmodel',
                     'funitid_number',
                     'funitid_name',
                     'fqty',
                     'fstockid_number',
                     'fownertypeid',
                     'fownerid_number',
                     'fseq',
                     'fentryid',
                     'fid',
                     'id',
                     )
                     ->where('purchasewarehousing_id',$Purchasewarehousing['id'])
                     ->where('fmaterialid',$SalesoutAttached['fmaterialid'])
                     ->where('fmaterialname',$SalesoutAttached['fmaterialname'])
                     ->where('funitid_number',$SalesoutAttached['funitid_number'])
                    //  ->where('fqty',$v['quantityComein'])
                     ->where('salesout_attached_id',$SalesoutAttached['id'])
                     ->first();

                    if(empty($PurchasewarehousingMateriel)){
                        return  throw new FailedException('亲！该条销售出库单号没有品号为'.$v['fmaterialid'].'的数据，不能入库');
                    }
                     
                //  if($v['quantityComein'] != $PurchasewarehousingMateriel['fqty']){
                //      return  throw new FailedException('亲！销售出库数量和采购入库数量不一致无法提交');
                //  }
 
                //  //金蝶数据
                //  $Model[$k]['FORGID'] = $Purchasewarehousing['fpurchaseorgid_number'];//组织编码
                //  $Model[$k]['FSRCBILLNO'] = $Purchasewarehousing['fbillno'];//销售出原单号
                //  $Model[$k]['FSRCSEQ'] = $PurchasewarehousingMateriel['fseq'];//原单行号
                //  $Model[$k]['FMATERIALID'] = $PurchasewarehousingMateriel['fmaterialid'];    
                //  $Model[$k]['FUNITID'] = $PurchasewarehousingMateriel['funitid_number'];
                //  $Model[$k]['FQTY'] = $v['quantityComein'];//入库数量
                //  $Model[$k]['FOwnerTypeId'] = $PurchasewarehousingMateriel['fownertypeid'];//货主类型
                //  $Model[$k]['FOwnerId'] = $PurchasewarehousingMateriel['fownerid_number'];//货主编码
                //  $Model[$k]['FSRCID'] = $PurchasewarehousingMateriel['fid'];//行号id
                //  $Model[$k]['FSRCENTRYID'] = $PurchasewarehousingMateriel['fentryid'];//单据合并
                //  $Model[$k]['FSTOCKID']= $Storagelocation['fnumber'];//仓库名称
   
                 $inventory = [
                     'org_code'=>$Purchasewarehousing['fpurchaseorgid_number'],
                     'cargo_code'=>$PurchasewarehousingMateriel['fownerid_number'],
                     'supplier_code'=>$Purchasewarehousing['warehosnumber'],
                     'doc_id'=>$Purchasewarehousing['id'],
                     'docno'=>$Purchasewarehousing['warehosnumber'], 
                     'doc_type'=>InvTransDocType::PURCHASE_RECEIPT_TISSUE->value,
                     'material_no'=>$PurchasewarehousingMateriel['fmaterialid'],
                     'location'=>$Storagelocation['warehousecode'],
                     'qty'=>$v['quantityComein'],
                     'unit'=>$PurchasewarehousingMateriel['funitid_number'],
                     'lotnum'=>$v['barcode'],
                 ];

                    InventoryService::addInv($inventory);

                    SalesoutTiaoma::where('id',$SalesoutTiaoma['id'])->where('barcode',$v['barcode'])
                    ->where('salesout_attached_id',$v['salesout_attached_id'])
                    ->where('salesout_id',$Salesout['id'])
                    ->update(
                        [
                        'purchasewarehousing_id'=>$Purchasewarehousing['id'],
                        'storagelocation_put'=>$v['storagelocation'],
                        'putquantity'=>$v['quantityComein'],
                        'purchasewarehousing_materiel'=>$PurchasewarehousingMateriel['id'],
                        ]
                    );
                    
                //  PurchasewarehousingMateriel::where('id',$PurchasewarehousingMateriel['id'])->update(
                //      [
                //      'barcode'=>$v['barcode'],
                //      'storagelocation'=>$v['storagelocation'],
                //      'putquantity'=>$v['quantityComein'],
                //      ]
                //  );
             }
 
             //改变状态
             Purchasewarehousing::where('id',$Purchasewarehousing['id'])->update(
                 [
                 'state'=>1,
                 'writestate'=>1,
                 'created_at'=>time(),
                 ]
             );

             
             //汇总推送到金蝶
             $data_res = PurchasewarehousingMateriel::select(
                'fmaterialid',
                'fmaterialname',
                'fmaterialmodel',
                'fmodel',
                'funitid_number',
                'funitid_name',
                'fstockid_number',
                'fownertypeid',
                'fownerid_number',
                'fseq',
                'fentryid',
                'fid',   
                'purchasewarehousing_id',   
                // 'storagelocation',   
                DB::raw('SUM(fqty) as fqty'),
                )
                ->where('purchasewarehousing_id',$Purchasewarehousing['id'])
                ->groupby([
                    'purchasewarehousing_id',
                    'fmaterialid',
                    'fmaterialname',
                    'fmaterialmodel',
                    'fmodel',
                    'funitid_number',
                    'funitid_name',
                    'fstockid_number',
                    'fownertypeid',
                    'fownerid_number',
                    'fseq',
                    'fentryid',
                    'fid', 
                ])
                ->get()
                ->toArray();

                foreach($data_res as $k=>$v){
                    $Model[$k]['FGIVEAWAY'] = 'false';
                    $Model[$k]['FGIVEAWAYQTY'] = 0;//赠品数量
                    //金蝶数据
                    $Model[$k]['FORGID'] = $Purchasewarehousing['fpurchaseorgid_number'];//组织编码
                    $Model[$k]['FSRCBILLNO'] = $Purchasewarehousing['fbillno'];//销售出原单号
                    $Model[$k]['FSRCSEQ'] = $v['fseq'];//原单行号
                    $Model[$k]['FMATERIALID'] = $v['fmaterialid'];    
                    $Model[$k]['FUNITID'] = $v['funitid_number'];
                    $Model[$k]['FQTY'] = $v['fqty'];//入库数量
                    $Model[$k]['FOwnerTypeId'] = $v['fownertypeid'];//货主类型
                    $Model[$k]['FOwnerId'] = $v['fownerid_number'];//货主编码
                    $Model[$k]['FSRCID'] = $v['fid'];//行号id
                    $Model[$k]['FSRCENTRYID'] = $v['fentryid'];//单据合并
                    $Model[$k]['FSTOCKID']= $Storagelocation['fnumber'];//仓库名称
                }

               
             
                
 
             $FEntity = [];
             foreach($Model as $k=>$v){
                 $FEntity[$v['FORGID']][$k]['FSRCSEQ'] = $v['FSRCSEQ'];
                 $FEntity[$v['FORGID']][$k]['FMATERIALID'] = $v['FMATERIALID'];
                 $FEntity[$v['FORGID']][$k]['FUNITID'] = $v['FUNITID'];
                 $FEntity[$v['FORGID']][$k]['FQTY'] = $v['FQTY'];
                 $FEntity[$v['FORGID']][$k]['FSTOCKID'] = $v['FSTOCKID'];
                 $FEntity[$v['FORGID']][$k]['FGIVEAWAY'] = $v['FGIVEAWAY'];
                 $FEntity[$v['FORGID']][$k]['FSRCBILLNO'] = $v['FSRCBILLNO'];
                 $FEntity[$v['FORGID']][$k]['FSRCID'] = $v['FSRCID'];
                 $FEntity[$v['FORGID']][$k]['FSRCENTRYID'] = $v['FSRCENTRYID'];
                 $FEntity[$v['FORGID']][$k]['FGIVEAWAYQTY'] = $v['FGIVEAWAYQTY'];
                 $FEntity[$v['FORGID']][$k]['FOwnerTypeId'] = $v['FOwnerTypeId'];
                 $FEntity[$v['FORGID']][$k]['FOwnerId'] = $v['FOwnerId'];
             }
            
             foreach($FEntity as $k=>$v){
                         $order = [
                             'FID'=>0,
                             'FORGID'=>$k,//组织（传编码）
                             'FBillNo'=>$Purchasewarehousing['warehosnumber'],
                             'FDATE'=>date('Y-m-d H:i:s',time()),
                             'FBILLTYPEID'=>"PUR_InStock",
                             //'FSRCBILLNO'=>$k,
                             'FEntity'=>array_values($v),
                         ];
                     //金蝶推送
                     (new KingDeeService())->form('TVJB_DJWMSDJ')->invokeSave($order);
             }
 

             DB::commit();
             return true;
         } catch (\Exception $e) {
             DB::rollBack();
             throw $e;
         }
 
      }
 

      // 组织间数据推送 PDA 扫描接口
    //   public static function pushdatacodeupdateMeiyong($data)
    //   {


   
    //      try {
    //          //开始起事务
    //         DB::beginTransaction();
    //          foreach($data as $k=>$v){                
    //              $Purchasewarehousing = Purchasewarehousing::select('fsrcbillno','fid','id','fpurchaseorgid_number','fsupplierid_number','warehosnumber')
    //              ->where('fsrcbillno',$v['fbillno'])
    //              ->where('incomingtype',1)
    //              ->first();
    //              if(empty($Purchasewarehousing)){
    //                  return  throw new FailedException('亲！没有该条入库单数据');
    //              }
    //              $PurchasewarehousingMateriel = PurchasewarehousingMateriel::select(
    //                  'fmaterialid',
    //                  'fmaterialname',
    //                  'fmaterialmodel',
    //                  'fmodel',
    //                  'funitid_number',
    //                  'funitid_name',
    //                  'fqty',
    //                  'fstockid_number',
    //                  'fownertypeid',
    //                  'fownerid_number',
    //                  'id',
    //                  )
    //                  ->where('purchasewarehousing_id',$Purchasewarehousing->id)
    //                  ->where('fmaterialid',$v['fmaterialid'])
    //                  ->where('fqty',$v['quantityComein'])
    //                  ->where('fmaterialname',$v['fmaterialname'])
    //                  ->first();
                     
    //              if($v['quantityComein'] != $PurchasewarehousingMateriel['fqty']){
    //                  return  throw new FailedException('亲！销售出库数量和采购入库数量不一致无法提交');
    //              }
 
    //              $Storagelocation = Storagelocation::query()->select('warehousecode')
    //              ->where('id',$v['storagelocation'])
    //              ->first();
 
    //              $inventory = [
    //                  'org_code'=>$Purchasewarehousing['fpurchaseorgid_number'],
    //                  'cargo_code'=>$PurchasewarehousingMateriel['fownertypeid'],
    //                  'supplier_code'=>$Purchasewarehousing['warehosnumber'],
    //                  'doc_id'=>$Purchasewarehousing['id'],
    //                  'docno'=>$Purchasewarehousing['warehosnumber'], 
    //                  'doc_type'=>InvTransDocType::PURCHASE_RECEIPT->value,
    //                  'material_no'=>$PurchasewarehousingMateriel['fmaterialid'],
    //                  'location'=>$Storagelocation['warehousecode'],
    //                  'qty'=>$v['quantityComein'],
    //                  'unit'=>$PurchasewarehousingMateriel['funitid_number'],
    //                  'lotnum'=>$v['barcode'],
    //              ];
    //              $data = InventoryService::addInv($inventory);
    //              PurchasewarehousingMateriel::where('id',$PurchasewarehousingMateriel['id'])->update(
    //                  [
    //                  'barcode'=>$v['barcode'],
    //                  'storagelocation'=>$v['storagelocation'],
    //                  'putquantity'=>$v['quantityComein'],
    //                  ]
    //              );
    //          }
 
    //          Purchasewarehousing::where('id',$Purchasewarehousing['fid'])->update(
    //              [
    //              'state'=>1,
    //              'writestate'=>1,
    //              ]
    //          );
 
    //          //  金蝶推送
    //          $order = [
    //              'FID'=>$Purchasewarehousing['fid'],
    //              'F_TVJB_WMSSMJL'=>"YSM",
    //          ];
           
             
    //          (new KingDeeService())->form('PUR_InStock')->invokeSave($order,['NeedUpDateFields'=>['FID','F_TVJB_WMSSMJL']]);
             
    //          DB::commit();
    //          return true;
    //      } catch (\Exception $e) {
    //          DB::rollBack();
    //          throw $e;
    //      }
 
    //   }




}
